package com.sigmatrix.h5.web.controller.front;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.sigmatrix.h5.auth.ILoginUser;
import com.sigmatrix.h5.config.LoginUser;
import com.sigmatrix.h5.entity.v2.VerRecord;
import com.sigmatrix.h5.enums.CrmAcctType;
import com.sigmatrix.h5.exception.MessageException;
import com.sigmatrix.h5.service.impl.v2.VerRecordServiceImpl;
import com.sigmatrix.h5.utils.CommonUtils;
import com.sigmatrix.h5.web.BaseController;
import com.sigmatrix.h5.web.Result;
import com.sigmatrix.h5.web.args.VerRecordParam;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "核销系统")
@RestController
@RequestMapping("/front/verification")
public class VerificationController extends BaseController {
	/** logger record */
	private static final Logger LOGGER = LoggerFactory.getLogger(VerificationController.class);

	@Autowired
	VerRecordServiceImpl verRecordService;

	@ApiOperation("核销")
	@PostMapping("/do")
	public Result<VerRecord> findRebateList(@LoginUser ILoginUser user, @RequestBody VerRecordParam vo) {
		LOGGER.info("核销接口请求参数={}", JSON.toJSONString(vo));
		VerRecord record = null;
		try {
			if (CommonUtils.isEmpty(vo.getLat()) || CommonUtils.isEmpty(vo.getLng())) {
				return error("请指定经纬度");
			}
			if (!CrmAcctType.isShopAcct(user.getAcctType())) {// 终端店类型账户
				return error("暂不支持该类型用户核销");
			}
			record = null;
			if (verRecordService.notVerfication(user, vo)) {
				record = verRecordService.verification(user, vo);
			} else {
				return error("此码已核销");
			}
		} catch (MessageException e) {
			logger.error("核销业务异常", e);
			return error(e.getMessage());
		} catch (Exception e) {
			logger.error("核销异常", e);
			return error("核销异常");
		}
		return ok(record);
	}

	@ApiOperation("核销记录")
	@PostMapping("/selectPage/size/{size}/current/{current}")
	public Result<Page<VerRecord>> findRebateList(@LoginUser ILoginUser user, @PathVariable int size,
			@PathVariable int current) {
		VerRecord record = new VerRecord();
		Page<VerRecord> pageRecord = new Page<VerRecord>(current, size);
		List<String> filedDesc = new ArrayList<>();
		filedDesc.add("verification_date");
		pageRecord.setDescs(filedDesc);
		record.setTablePrefix("_" + user.getEseCode());
		record.setUserId(user.getAcctId());
		return ok(verRecordService.selectPage(pageRecord, new EntityWrapper<>(record)));
	}
}
